//
//  ImageUploader.m
//  GolfFriend
//
//  Created by vescky on 13-12-19.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "ImageUploader.h"
#import "QiniuPutPolicy.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/UTCoreTypes.h>


static NSString *QiniuAccessKey = @"<Please specify your access key>";
static NSString *QiniuSecretKey = @"<Please specify your secret key>";
static NSString *QiniuBucketName = @"<Please specify your bucket name>";

ImageUploader *imgUploader;
QiniuSimpleUploader *_sUploader;

@implementation ImageUploader {
    
}

@synthesize delegate;

+ (id)shareImageUploader {
    if (!imgUploader) {
        imgUploader = [[ImageUploader alloc] init];
        QiniuAccessKey = @"9JGfgkGQrtm1jFoneCtDLZJhnI0TAzgdx9EXSWtq";
        QiniuSecretKey = @"wV696XPdE3FG7bL0wYu8_V9mEjtmNp9bauypq-er";
        QiniuBucketName = @"mingyuanhui";
    }
    return imgUploader;
}

- (bool)uploadImage:(NSString*)imgPath {
    if (!imgPath || imgPath.length < 1) {
        return NO;
    }
    [self uploadFile:imgPath bucket:QiniuBucketName key:[imgPath lastPathComponent]];
    return YES;
}

- (bool)uploadImage:(NSString*)imgPath asName:(NSString*)fileName {
    if (!imgPath || imgPath.length < 1) {
        return NO;
    }
    [self uploadFile:imgPath bucket:QiniuBucketName key:fileName];
    return YES;
}

#pragma mark - QiniuUploadDelegate
// Progress updated.
- (void)uploadProgressUpdated:(NSString *)filePath percent:(float)percent
{
    NSString *message = [NSString stringWithFormat:@"Progress of uploading %@ is: %.2f%%",  filePath, percent * 100];
    NSLog(@"%@", message);
    if ([delegate respondsToSelector:@selector(imageUploaderProcessUpdated:percent:)]) {
        [delegate imageUploaderProcessUpdated:filePath percent:percent];
    }
}

// Upload completed successfully.
- (void)uploadSucceeded:(NSString *)filePath ret:(NSDictionary *)ret
{
    NSString *hash = [ret objectForKey:@"hash"];
    NSString *message = [NSString stringWithFormat:@"Successfully uploaded %@ with hash: %@",  filePath, hash];
    NSLog(@"%@", message);
    if ([delegate respondsToSelector:@selector(uploadSuccess:ret:)]) {
        [delegate uploadSuccess:filePath ret:ret];
    }
}

// Upload failed.
//
// (NSError *)error:
//      ErrorDomain - QiniuSimpleUploader
//      Code - It could be a general error (< 100) or a HTTP status code (>100)
//      Message - You can use this line of code to retrieve the message: [error.userInfo objectForKey:@"error"]
- (void)uploadFailed:(NSString *)filePath error:(NSError *)error
{
    NSString *message = @"";
    
    // For first-time users, this is an easy-to-forget preparation step.
    if ([QiniuAccessKey hasPrefix:@"<Please"]) {
        message = @"Please replace kAccessKey, kSecretKey and kBucketName with proper values. These values were defined on the top of QiniuViewController.m";
    } else {
        message = [NSString stringWithFormat:@"Failed uploading %@ with error: %@",  filePath, error];
    }
    NSLog(@"%@", message);
    if ([delegate respondsToSelector:@selector(uploadFail:error:)]) {
        [delegate uploadFail:filePath error:error];
    }
}


#pragma mark - Private
//save image from picker
- (void)uploadContent:(NSDictionary *)theInfo {
    
    //obtaining saving path
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat: @"yyyy-MM-dd-HH-mm-ss"];
    //Optionally for time zone conversions
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    
    NSString *timeDesc = [formatter stringFromDate:[NSDate date]];
    
    //extracting image from the picker and saving it
    NSString *mediaType = [theInfo objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage] || [mediaType isEqualToString:(NSString *)ALAssetTypePhoto]) {
        
        NSString *key = [NSString stringWithFormat:@"%@%@", timeDesc, @".jpg"];
        key = @"aaa.jpg";
        NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:key];
        NSLog(@"Upload Path: %@", filePath);
        
        NSData *webData = UIImageJPEGRepresentation([theInfo objectForKey:UIImagePickerControllerOriginalImage], 1);
        [webData writeToFile:filePath atomically:YES];
        
        [self uploadFile:filePath bucket:QiniuBucketName key:key];
    }
}

- (NSString *)tokenWithScope:(NSString *)scope
{
    QiniuPutPolicy *policy = [QiniuPutPolicy new];
    policy.scope = scope;
    
    return [policy makeToken:QiniuAccessKey secretKey:QiniuSecretKey];
}

- (void)uploadFile:(NSString *)filePath bucket:(NSString *)bucket key:(NSString *)key {
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]) {
        
        _sUploader = [QiniuSimpleUploader uploaderWithToken:[self tokenWithScope:bucket]];
        _sUploader.delegate = self;
        
        [_sUploader uploadFile:filePath key:key extra:nil];
    }
}

@end
